package jp.co.apl.haven.web;

import java.util.Properties;
import java.util.ServiceLoader;

import jp.co.apl.haven.inject.PersistenceModule;
import jp.co.apl.haven.web.exception.ApplicationException;
import jp.co.apl.haven.web.page.Upload;
import jp.co.apl.haven.web.service.HavenWebService;
import jp.co.apl.haven.web.service.HavenWebServiceImpl;

import org.t2framework.commons.util.PropertiesUtil;

import com.google.inject.AbstractModule;
import com.google.inject.servlet.RequestScoped;
import com.google.inject.servlet.ServletModule;

/**
 * 
 * @author narazaki.daishi
 */
public class ApplicationModule extends AbstractModule {

    @Override
    protected void configure() {

        // module
        install(new ServletModule());
        install(loadPersistenceModule());

        // pages
        bind(Upload.class).in(RequestScoped.class);

        // services
        bind(HavenWebService.class).to(HavenWebServiceImpl.class);

    }

    protected PersistenceModule loadPersistenceModule() {
        Properties props = new Properties();
        PropertiesUtil.load(
            props,
            getClass().getResourceAsStream("/config.properties"));

        ServiceLoader<PersistenceModule> persistenceModuleLoader =
            ServiceLoader.load(PersistenceModule.class);

        for (PersistenceModule pm : persistenceModuleLoader) {
            pm.setUrl(props.getProperty("db.url"));
            pm.setUsername(props.getProperty("db.username"));
            pm.setPassword(props.getProperty("db.password"));
            return pm;
        }
        throw new ApplicationException("永続化モジュールのロードに失敗しました。");
    }

}
